package com.miaoquan.mqapitbk.service.impl;

import com.miaoquan.mqapitbk.domain.builder.TbkProductBuilder;
import com.miaoquan.mqapitbk.service.SearchService;
import com.miaoquan.mqapitbk.utils.TbkUtil;
import com.miaoquan.mqcommon.api.CommonPage;
import com.miaoquan.mqcommon.api.CommonResult;
import com.miaoquan.mqcommon.api.ResultCode;
import com.miaoquan.mqmbg.mapper.TbkProductMapper;
import com.miaoquan.mqmbg.model.TbkProduct;
import com.taobao.api.ApiException;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.TbkDgMaterialOptionalRequest;
import com.taobao.api.response.TbkDgMaterialOptionalResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

/**
 * 搜索Service实现类
 *
 * @author Fa
 * @date 2020-04-04 23:09
 */
@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private TaobaoClient taobaoClient;
    @Autowired
    private ExecutorService executorService;

    @Autowired
    private TbkProductMapper tbkProductMapper;


    @Override
    public CommonResult<CommonPage<TbkProduct>> searchProduct(Long pageNum, boolean isTmall, String q) throws ApiException {
        TbkDgMaterialOptionalRequest req = new TbkDgMaterialOptionalRequest();
//        req.setStartDsr(10L);
        req.setPageSize(20L);
        req.setPageNo(pageNum);
        req.setPlatform(2L);
//        req.setEndTkRate(1234L);
//        req.setStartTkRate(1234L);
//        req.setEndPrice(10L);
//        req.setStartPrice(10L);
//        req.setIsOverseas(false);
        req.setIsTmall(isTmall);
//        req.setSort("tk_rate_des");
//        req.setItemloc("杭州");
//        req.setCat("16,18");
        req.setQ(q);
        // 不传时默认物料id=2836；如果直接对消费者投放，可使用官方个性化算法优化的搜索物料id=17004
        req.setMaterialId(17004L);
        req.setHasCoupon(false);
//        req.setIp("13.2.33.4");
        req.setAdzoneId(TbkUtil.ADZONE_ID);
//        req.setNeedFreeShipment(true);
//        req.setNeedPrepay(true);
//        req.setIncludePayRate30(true);
//        req.setIncludeGoodRate(true);
//        req.setIncludeRfdRate(true);
//        req.setNpxLevel(2L);
//        req.setEndKaTkRate(1234L);
//        req.setStartKaTkRate(1234L);
//        req.setDeviceEncrypt("MD5");
//        req.setDeviceValue("xxx");
//        req.setDeviceType("IMEI");
//        req.setLockRateEndTime(1567440000000L);
//        req.setLockRateStartTime(1567440000000L);
        TbkDgMaterialOptionalResponse rsp = taobaoClient.execute(req);
        if (rsp.isSuccess()) {
            List<TbkProduct> tbkProductList = rsp.getResultList().stream().map(
                    mapData ->
                            new TbkProductBuilder().buildByOptimusMaterialMapData(mapData)
            ).collect(Collectors.toList());

            // 异步插入搜索数据
            executorService.submit(
                    () -> tbkProductList.forEach(
                            tbkProduct ->
                                    tbkProductMapper.insertSelective(tbkProduct)
                    )
            );

            return CommonResult.success(CommonPage.restPage(
                    tbkProductList,
                    req.getPageNo().intValue(),
                    req.getPageSize().intValue(),
                    rsp.getTotalResults().intValue()
            ));
        }
        return CommonResult.failed(ResultCode.TBK_API, rsp.getSubMsg());
    }

    @Override
    public CommonResult<CommonPage<TbkProduct>> searchProduct(TbkDgMaterialOptionalRequest tbkDgMaterialOptionalRequest) throws ApiException {
        if (tbkDgMaterialOptionalRequest.getPageNo() == null) {
            tbkDgMaterialOptionalRequest.setPageNo(1L);
        }
        if (tbkDgMaterialOptionalRequest.getPageSize() == null) {
            tbkDgMaterialOptionalRequest.setPageSize(20L);
        }
        tbkDgMaterialOptionalRequest.setPlatform(2L);
        tbkDgMaterialOptionalRequest.setMaterialId(17004L);
        tbkDgMaterialOptionalRequest.setAdzoneId(TbkUtil.ADZONE_ID);
        TbkDgMaterialOptionalResponse rsp = taobaoClient.execute(tbkDgMaterialOptionalRequest);
        if (rsp.isSuccess()) {
            List<TbkProduct> tbkProductList = rsp.getResultList().stream().map(mapData ->
                    new TbkProductBuilder().buildByOptimusMaterialMapData(mapData)
            ).collect(Collectors.toList());

            // 异步插入搜索数据
            executorService.submit(
                    () -> tbkProductList.forEach(
                            tbkProduct ->
                                    tbkProductMapper.insertSelective(tbkProduct)
                    )
            );
            return CommonResult.success(CommonPage.restPage(
                    tbkProductList,
                    tbkDgMaterialOptionalRequest.getPageNo().intValue(),
                    tbkDgMaterialOptionalRequest.getPageSize().intValue(),
                    rsp.getTotalResults().intValue()
            ));
        }
        return CommonResult.failed(ResultCode.TBK_API, rsp.getSubMsg());
    }

}
